﻿using BLL;
using Model;
using System;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;

namespace Thksoft.UserCotrols
{
    public partial class UploadFile : System.Web.UI.UserControl
    {
        private bool flag;

        private bool Flag
        {
            get { return flag; }
            set { flag = value; }
        }

        private Qs_FileBLL qfb = new Qs_FileBLL();
        private Qs_SequencesBLL qsb = new Qs_SequencesBLL();
        //private string businessId = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string url = Parent.Page.ToString();
                if (flag == true)
                {
                    FileUpload.Visible = false;
                }

                string businessId = Request.QueryString["BusinessId"].ToString();

                BindFileData(decimal.Parse(businessId));
            }
        }

        private void BindFileData(decimal businessId)
        {
            DataTable dt = qfb.GetFile(businessId);
            dataList.DataSource = dt;
            dataList.DataBind();
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            //文件名称
            string filename = "";
            //保存的路径
            string severUrl = "";
            //是否上传成功
            bool isTrue = true;
            //文件的物理路径
            string FileUrl = "";
            //文件的大小
            decimal FileSize = 0;
            DateTime dt = DateTime.Now;

            string userName = "SUPER";
            try
            {
                userName = ((Sys_User)System.Web.HttpContext.Current.Session["SysUserInfo"]).USER_NAME.ToString();
            }
            catch
            {
                MessageBox.Show(Page, "您的时间已过期，请重新登录");
                return;
            }

            //保存文件
            if (FileUpload.HasFile)
            {
                filename = FileUpload.FileName;
                FileSize = Convert.ToDecimal(FileUpload.FileBytes.Length) / (1024 * 1024);
                string name_last = System.IO.Path.GetExtension(filename).Trim();

                string year = dt.Year.ToString();
                string mon = dt.Month.ToString();
                string day = dt.Day.ToString();
                string hh = dt.Hour.ToString();
                string mm = dt.Minute.ToString();
                string ss = dt.Second.ToString();
                //文件的格式 年月日时分秒附件名称
                string p = year + mon + day + hh + mm + ss;

                Random r = new Random();
                string s1 = r.Next(99, 999).ToString();
                string s2 = r.Next(99, 999).ToString();
                string f = filename.Remove(0, filename.LastIndexOf('.'));
                try
                {
                    //创建文件夹
                    if (!Directory.Exists(HttpContext.Current.Server.MapPath("/UpLoad/")))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/UpLoad/"));
                    }

                    //保存的路径
                    FileUrl = HttpContext.Current.Server.MapPath(@"/UpLoad/" + p + s1 + s2 + f);
                    severUrl = @"/UpLoad/" + p + s1 + s2 + f;

                    FileUpload.SaveAs(FileUrl);
                }
                catch
                {
                    MessageBox.Show(Page, "文件上传失败");
                    isTrue = false;
                }

                if (isTrue)
                {
                    try
                    {
                        Qs_File model = new Qs_File();

                        model.N_business_id = decimal.Parse(Request.QueryString["BusinessId"].ToString());
                        model.C_file_name = FileUpload.FileName;
                        model.C_file_path = severUrl;
                        model.C_file_operator = userName;
                        model.D_file_operator_Time = DateTime.Now;
                        model.C_remark = "";
                        int row = qfb.INSERT(model, userName);
                        if (row > 0)
                        {
                            MessageBox.Show(Page, "上传文件成功");
                            BindFileData(decimal.Parse(Request.QueryString["BusinessId"].ToString()));
                            return;
                        }
                    }
                    catch
                    {
                        MessageBox.Show(Page, "上传文件失败");
                        return;
                    }
                }
            }
            else
            {
                MessageBox.Show(Page, "请选择文件路径");
                return;
            }
        }

        protected void ButDelete_Click(object sender, EventArgs a)
        {
            try
            {
                string userName = "SUPER";
                try
                {
                    userName = ((Sys_User)System.Web.HttpContext.Current.Session["SysUserInfo"]).USER_NAME.ToString();
                }
                catch
                {
                    MessageBox.Show(Page, "您的时间已过期，请重新登录");
                    return;
                }
                Button btnFileId = (Button)sender;
                Qs_File file = new Qs_File();
                decimal fileId = decimal.Parse(btnFileId.CommandArgument);

                file = qfb.GetFileById(fileId);

                if (file.C_file_operator != ((Sys_User)System.Web.HttpContext.Current.Session["SysUserInfo"]).USER_NAME.ToString())
                {
                    MessageBox.Show(Page, "对不起，你不能进行删除");
                    return;
                }
                else
                {
                    int count = qfb.DELETE(fileId, userName);
                    if (count > 0)
                    {
                        if (File.Exists(HttpContext.Current.Server.MapPath(file.C_file_path)))
                        {
                            string lUrl = HttpContext.Current.Server.MapPath(file.C_file_path);
                            File.Delete(lUrl);
                        }
                        MessageBox.Show(Page, "删除成功");
                    }
                }
            }
            catch
            {
                MessageBox.Show(Page, "删除文件失败");
            }
            BindFileData(decimal.Parse(Request.QueryString["BusinessId"].ToString()));
            return;
        }

        protected void lnkfileName_Click(object sender, EventArgs a)
        {
            try
            {
                LinkButton btnAccessoriesUrl = (LinkButton)sender;
                String FullFileName = System.Web.HttpContext.Current.Server.MapPath(btnAccessoriesUrl.CommandArgument);
                FileInfo DownloadFile = new FileInfo(FullFileName);
                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.ClearHeaders();
                System.Web.HttpContext.Current.Response.Buffer = false;
                System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
                System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(btnAccessoriesUrl.Text, System.Text.Encoding.UTF8));
                System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
                System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
                System.Web.HttpContext.Current.Response.Flush();
                System.Web.HttpContext.Current.Response.End();
            }
            catch
            {
                MessageBox.Show(Page, "未找到相关附件信息");
                return;
            }
        }

        protected void dataList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            string url = Parent.Page.ToString();
            if (url == "ASP.businessexpansion_business_updataapplydetail_aspx")
            {
                Button del = new Button();

                del = (Button)e.Item.FindControl("ButDelete");
                del.Enabled = false;
            }
        }
    }
}